package tsou.cn.glidetest.Util;

import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.bumptech.glide.request.target.Target;

import tsou.cn.glidetest.Glide.okhttp.ProgressInterceptor;
import tsou.cn.glidetest.Glide.okhttp.ProgressListener;
import tsou.cn.glidetest.R;
import tsou.cn.glidetest.view.RoundProgressBar;

/**
 * 图片加载类封装
 */
public class ImageLoadUtil {

    public static ImageView display(ImageView img, RoundProgressBar roundProgressBar, String url) {
        ProgressInterceptor.addListener(url, new MyProgressListener(roundProgressBar));
        Glide.with(UIUtils.getContext())
                .load(url)
                .placeholder(R.drawable.app_loading_pic)
                .error(R.drawable.app_loading_pic)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                .into(new MyGlideDrawableImageViewTarget(img, roundProgressBar, url));
        return img;
    }

    private static class MyProgressListener implements ProgressListener {

        private RoundProgressBar mRoundProgressBar;

        public MyProgressListener(RoundProgressBar roundProgressBar) {
            this.mRoundProgressBar = roundProgressBar;
        }

        @Override
        public void onProgress(int progress) {
            mRoundProgressBar.setProgress(progress);
        }
    }

    private static class MyGlideDrawableImageViewTarget extends GlideDrawableImageViewTarget {

        private RoundProgressBar mRoundProgressBar;
        private String mUrl;

        public MyGlideDrawableImageViewTarget(ImageView view, RoundProgressBar roundProgressBar, String url) {
            super(view);
            this.mRoundProgressBar = roundProgressBar;
            this.mUrl = url;
        }

        public void onLoadStarted(Drawable placeholder) {
            super.onLoadStarted(placeholder);
            mRoundProgressBar.setVisibility(View.VISIBLE);
            mRoundProgressBar.setProgress(1);
        }

        @Override
        public void onLoadFailed(Exception e, Drawable errorDrawable) {
            UIUtils.showToast("加载失败");
            mRoundProgressBar.setVisibility(View.GONE);
            ProgressInterceptor.removeListener(mUrl);
            super.onLoadFailed(e, errorDrawable);
        }

        @Override
        public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> animation) {
            super.onResourceReady(resource, animation);
            mRoundProgressBar.setVisibility(View.GONE);
            ProgressInterceptor.removeListener(mUrl);
        }
    }

}
